import React from "react";
import {DownOutlined} from '@ant-design/icons';
import {Button, Col, Dropdown, Input, Menu, Row, Select} from "antd";
import UserForm from "./UserForm";
import UserPwdForm from "./UserPwdForm";
import UserRoleForm from "./UserRoleForm";
import UserMenuForm from "./UserMenuForm";
import UserPlatformForm from "./UserPlatformForm";
import UserStatusForm from "./UserStatusForm";
import BaseComponent from "../../../../redare/components/BaseComponent";
import UserPresenter from "../../.gen/presenter/component/core/UserPresenter";
import Window from "../../../../redare/components/modal/Window";
import PlatformSelect from "../platform/PlatformSelect";
import RoleSelect from "../role/RoleSelect";
import ResizeGrid from "../../../../redare/components/grid/ResizeGrid";
import {dateFormat} from "../../../../redare/utils/DateUtils";
import {getLoginUserInfo, isLoginUserInRootPlatform} from "../../utils/WorkbenchUtil";
import FunPermission from "../permission/FunPermission";

export default class UserGrid extends BaseComponent {

    static defaultProps = {
        onUserSelected: undefined
    };

    constructor(props) {
        super(props);
        this.presenter = new UserPresenter(this);
        this._isRootPlatform = isLoginUserInRootPlatform();
        this._user = getLoginUserInfo();
    }

    componentDidMount() {
        this._searchUserData({curPage: 1});
    }

    _searchUserData({curPage = 1} = {}) {
        let {key, platform, roleIds, status} = this._form;
        this.showLoadingIndicator('加载中...');
        this.presenter.findUserPage({
            key,
            platform,
            status,
            roleIds,
            incMenu: true,
            incRoot: true
        }, {curPage}, (result) => {
            this.grid.setData(result.data.result, result.data);
        });
    }

    _onAddClick() {
        this._win = Window.show(
            <UserForm onCancel={() => {
                this._win.close();
            }}
                      onAddSuccess={this._onAddSuccess.bind(this)}
            />,
            {title: '添加用户'});
    }

    _onEditClick({record, index}) {
        this._win = Window.show(
            <UserForm onCancel={() => {
                this._win.close();
            }}
                      id={record.id}
                      onEditSuccess={this._onEditSuccess.bind(this)}
            />,
            {title: '编辑用户'});
    }

    _onDelClick({record, index}) {
        this.confirm('确定要删除该用户吗？', () => {
            this.presenter.delUser({accountId: record.id}, {}, () => {
                this._searchUserData({curPage: this.grid.getCurPage()});
            });
        });
    }

    _onAddSuccess() {
        this._win.close();
        this._searchUserData({curPage: 1});
    }

    _onEditSuccess() {
        this._win.close();
        this._searchUserData({curPage: this.grid.getCurPage()});
    }

    _modifyPwdClick({record, index}) {
        this._win = Window.show(
            <UserPwdForm
                id={record.id}
                onCancel={() => {
                    this._win.close();
                }}
                onSuccess={() => this._win.close()}
            />,
            {title: '修改密码'});
    }

    _modifyRoleClick({record, index}) {
        this._win = Window.show(
            <UserRoleForm
                id={record.id}
                onCancel={() => {
                    this._win.close();
                }}
                onSuccess={this._onEditSuccess.bind(this)}
            />,
            {title: '修改角色'});
    }

    _modifyMenuClick({record, index}) {
        this._win = Window.show(
            <UserMenuForm
                id={record.id}
                onCancel={() => {
                    this._win.close();
                }}
                onSuccess={this._onEditSuccess.bind(this)}
            />,
            {title: '修改菜单'});
    }

    _modifyPlatformClick({record, index}) {
        this._win = Window.show(
            <UserPlatformForm
                id={record.id}
                onCancel={() => {
                    this._win.close();
                }}
                onSuccess={this._onEditSuccess.bind(this)}
            />,
            {title: '修改平台'});
    }

    _modifyStatusClick({record, index}) {
        this._win = Window.show(
            <UserStatusForm
                id={record.id}
                onCancel={() => {
                    this._win.close();
                }}
                onSuccess={this._onEditSuccess.bind(this)}
            />,
            {title: '修改状态'});
    }

    showLoadingIndicator(text, options = {}) {
        this.grid.showLoadingIndicator();
    }

    closeLoadingIndicator() {
        this.grid.closeLoadingIndicator();
    }

    _getColumns() {
        let columns = [
            {
                title: 'ID',
                dataIndex: 'id',
                fixed: 'left',
                width: 80,
                _resizeable: true,
                ellipsis: true,
            },
            {
                title: '账号',
                dataIndex: 'account',
                fixed: 'left',
                width: 120,
                _resizeable: true,
                ellipsis: true,
                _showTooltip: true,
            },
            {
                title: '用户名',
                dataIndex: 'name',
                fixed: 'left',
                width: 120,
                _resizeable: true,
                ellipsis: true,
            }
        ];
        if (this._isRootPlatform) {
            columns.push({
                title: '所属平台',
                dataIndex: 'platformName',
                width: 200,
                _resizeable: true,
                ellipsis: true,
                render: (value, record) => {
                    return `${record.platformName}（${record.platform}）`;
                }
            });
        }
        columns.push(...[
            {
                title: '角色',
                dataIndex: 'roleNames',
                width: 150,
                _resizeable: true,
                ellipsis: true,
                _showTooltip: true,
            },
            {
                title: '菜单',
                dataIndex: 'menuName',
                width: 120,
                _resizeable: true,
                ellipsis: true,
            },
            {
                title: '状态',
                align: 'center',
                dataIndex: 'status',
                width: 80,
                render: (value, record, index) => {
                    return value === 0 ? '正常' : '锁定';
                }
            },
            {
                title: '管理员',
                align: 'center',
                dataIndex: 'admin',
                width: 80,
                render: (value, record, index) => {
                    return value ? '是' : '';
                }
            },
            {
                title: '手机号',
                dataIndex: 'mobile',
                width: 150,
                _resizeable: true,
                ellipsis: true,
                _showTooltip: true,
            },
            {
                title: '邮箱',
                dataIndex: 'email',
                width: 200,
                _resizeable: true,
                ellipsis: true,
                _showTooltip: true,
            },
            {
                title: '最近登录时间',
                dataIndex: 'lastLoginTime',
                width: 180,
                _resizeable: true,
                ellipsis: true,
                _showTooltip: true,
                render: (value) => {
                    return dateFormat(value);
                }
            },
            {
                title: '操作',
                dataIndex: '',
                fixed: 'right',
                width: 160,
                align: 'center',
                render: (value, record, index) => {
                    let {id} = record;
                    return <>
                        <Button size="small"
                                type="primary"
                                onClick={() => {
                                    if (this.props.onUserSelected) {
                                        this.props.onUserSelected(record);
                                    }
                                }}>详情</Button>
                        <Dropdown overlay={<Menu>
                            <FunPermission.MenuItem funId="WebPlatformUserModifyInfo"
                                                    onClick={this._onEditClick.bind(this, {
                                                        record,
                                                        index
                                                    })}>编辑用户</FunPermission.MenuItem>
                            <FunPermission.MenuItem funId="WebPlatformUserModifyPassword"
                                                    onClick={this._modifyPwdClick.bind(this, {
                                                        record,
                                                        index
                                                    })}>修改密码</FunPermission.MenuItem>
                            {
                                id !== 0 && (
                                    <FunPermission.MenuItem funId="WebPlatformUserModifyRole"
                                                            onClick={this._modifyRoleClick.bind(this, {
                                                                record,
                                                                index
                                                            })}>修改角色</FunPermission.MenuItem>
                                )
                            }
                            {
                                id !== 0 && (
                                    <FunPermission.MenuItem funId="WebPlatformUserModifyStatus"
                                                            onClick={this._modifyStatusClick.bind(this, {
                                                                record,
                                                                index
                                                            })}>修改状态</FunPermission.MenuItem>
                                )
                            }
                            <FunPermission.MenuItem funId="WebPlatformUserModifyMenu"
                                                    onClick={this._modifyMenuClick.bind(this, {
                                                        record,
                                                        index
                                                    })}>修改菜单</FunPermission.MenuItem>
                            {
                                id !== 0 && (
                                    <FunPermission.MenuItem funId="WebPlatformUserDel"
                                                            onClick={this._onDelClick.bind(this, {record, index})}>
                                        <span style={({color: '#ff4d4f'})}>删除用户</span>
                                    </FunPermission.MenuItem>
                                )
                            }
                        </Menu>}>
                            <Button size="small" style={({marginLeft: 10})}>
                                操作 <DownOutlined/>
                            </Button>
                        </Dropdown>
                    </>;
                },
            }
        ]);
        return columns;
    }

    render() {
        return <>
            <Row type="flex" justify="space-between" align="middle" style={({paddingBottom: 10})}>
                <Col span={20}>
                    <Input placeholder="输入关键字搜索" allowClear={true} style={({width: 200})}
                           onChange={(e) => this._form.key = e.target.value}/>
                    {
                        this._isRootPlatform ? (
                            <>
                                <span style={({marginLeft: 10})}>平台：</span>
                                <PlatformSelect style={({width: 200})} onValueChange={(value) => {
                                    let lastPlatform = this._form.platform;
                                    this._form.platform = value;
                                    if (!this._form.platform) {
                                        this._form.roleIds = null;
                                    }
                                    if (!lastPlatform || !this._form.platform) {
                                        this._searchUserData();
                                    }
                                    this.refreshState();
                                }}/>
                                {
                                    this._form.platform && (
                                        <>
                                            <span style={({marginLeft: 10})}>角色：</span>
                                            <RoleSelect style={({width: 200})}
                                                        platform={this._form.platform}
                                                        onValueChange={(value) => {
                                                            this._form.roleIds = value;
                                                            this._searchUserData();
                                                        }}/>
                                        </>
                                    )
                                }
                            </>
                        ) : (
                            <>
                                <span style={({marginLeft: 10})}>角色：</span>
                                <RoleSelect style={({width: 200})}
                                            platform={this._user.platform}
                                            onValueChange={(value) => {
                                                this._form.roleIds = value;
                                                this._searchUserData();
                                            }}/>
                            </>
                        )
                    }

                    <span style={({marginLeft: 10})} style={({marginLeft: 10})}>状态：</span>
                    <Select allowClear={true}
                            style={({width: 100})} onChange={(value) => {
                        this._form.status = value;
                        this._searchUserData();
                    }}>
                        <Select.Option value={0}>正常</Select.Option>
                        <Select.Option value={1}>锁定</Select.Option>
                    </Select>
                    <Button style={({marginLeft: 10})}
                            onClick={this._searchUserData.bind(this, {curPage: 1})}>搜索</Button>
                </Col>
                <FunPermission funId="WebPlatformUserAdd">
                    <Button type="primary" onClick={this._onAddClick.bind(this)}>添加用户</Button>
                </FunPermission>
            </Row>
            <ResizeGrid
                ref={(o) => {
                    this.grid = o
                }}
                _onPageChange={this._searchUserData.bind(this)}
                rowKey={(r) => r.id}
                size="middle"
                _autoCalScrollX={true}
                columns={this._getColumns()}/>
        </>;
    }
}
